package com.hzvdvmc.autosale.setting.ui;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;

import com.hzvdvmc.autosale.R;
import com.hzvdvmc.autosale.base.ActionbarActivity;
import com.hzvdvmc.autosale.common.OnItemClickListener;
import com.hzvdvmc.autosale.constant.SpKey;
import com.hzvdvmc.autosale.sale.ui.InputDialog;
import com.hzvdvmc.autosale.seriaport.SerialCallback;
import com.hzvdvmc.autosale.seriaport.SerialClientManager;
import com.hzvdvmc.autosale.seriaport.SerialCmdEnum;
import com.hzvdvmc.autosale.setting.adapter.SimpleTextRvAdapter;
import com.hzvdvmc.autosale.util.LogUtil;
import com.hzvdvmc.autosale.util.SPUtils;
import com.hzvdvmc.autosale.util.StringUtil;
import com.hzvdvmc.autosale.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 压缩机设置
 * 地址码（字符串）	工作模式	设置温度	当前温度	故障码
 */
public class ColdSetActivity extends ActionbarActivity {

    public static final String ADDRESS_CODE = "地址码  :";
    public static final String MODE = "工作模式  :";
    public static final String SETTEMPERATURE = "设置温度  :";
    public static final String CURRENTTEMPERATURE = "当前温度  :";
    public static final String ERRORCODE = "故障码  :  ";

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private SimpleTextRvAdapter mAdater;
    private List<String> dataList = new ArrayList<>();
    private String addCode = "00";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cold_set);
        ButterKnife.bind(this);
        setCustomeActiorBar("压缩机设置");
        setRightFuncBtn("保存", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveSetting();
            }
        });
        initView();
        initData();
    }

    private void saveSetting() {

        if (TextUtils.isEmpty(getMode())) {
            ToastUtils.showShort("请设置工作模式");
            return;
        }

        if (TextUtils.isEmpty(getSettemperature())) {
            ToastUtils.showShort("请设置温度");
            return;
        }

        char st = convertStrToAscii(getSettemperature());
        String data = addCode + getMode() + st;

        SPUtils.getInstance().put(SpKey.TEMPUTURE_SET, data);
        sendSerialData(data);
    }

    /**
     * 将10进制字符 转化成 该对应字节的ASCII码
     * 比如 ：30 -> "0"
     *
     * @param str
     * @return
     */
    private char convertStrToAscii(String str) {
        int i = Integer.parseInt(str);
        if (i < 0) {
            i = i + 256;
        }

        return (char) i;
    }

    private void sendSerialData(String data) {
        SerialClientManager manager = new SerialClientManager();
        manager.setData(data);
        manager.setCallback(SerialCmdEnum.SYSYTEM_PARAMS_MODIFY, new SerialCallback() {
            @Override
            public void onSuccess(String cmd, String data,String tuneNO, String orderNO) {
                String result = data.substring(2, 3);
                if ("0".equals(result)) {
                    LogUtil.p("压缩机设置成功");
                    ToastUtils.showShort("设置成功");

                } else {
                    ToastUtils.showShort("设置失败");
                }
            }

            @Override
            public void onFile(String msg,String tuneNO, String orderNO) {
                ToastUtils.showShort(msg);
            }
        });
        manager.execute();
    }

    private void initData() {
        refreshDataList(addCode, "", "", "", "");
        getInfo(addCode);
    }

    private void refreshDataList(String addCode, String mode,
                                 String setTemperature, String currentTemperature, String
                                         errorCode) {
        dataList.clear();
        dataList.add(ADDRESS_CODE + addCode);
        dataList.add(MODE + mode);
        dataList.add(SETTEMPERATURE + setTemperature);
        dataList.add(CURRENTTEMPERATURE + currentTemperature);
        dataList.add(ERRORCODE + errorCode);
        mAdater.notifyDataSetChanged();
    }

    public String getMode() {
        String mode = dataList.get(1);
        if (mode.equals(MODE + "停止工作")) {
            return "0";
        } else if (mode.equals(MODE + "制冷")) {
            return "1";
        } else if (mode.equals(MODE + "制热")) {
            return "2";
        }
        return "";
    }

    public String getSettemperature() {
        String temperature = "";
        String[] split = dataList.get(2).split(":");
        if (split.length == 2) {
            temperature = split[1];
        }
        return temperature.trim();
    }

    private void getInfo(String code) {
        SerialClientManager manager = new SerialClientManager();
        manager.setCallback(SerialCmdEnum.MACHINE_STATE, new SerialCallback() {
            @Override
            public void onSuccess(String cmd, String data,String tuneNO, String orderNO) {
//                2字节	1字节	1字节	1字节	1字节
//                data1	data3	data4	data5	data6
//                地址码	工作模式	设置温度	当前温度	故障码
                // 30 30 30 0a ec 01

                String addCode = data.substring(0, 2);
                String mode = data.substring(2, 3);

                String hexStr = StringUtil.convertStringToHex(data);
                String setTemperature = hexStr.substring(6, 8);
                String currentTemperature = hexStr.substring(8, 10);
                String errorCode = hexStr.substring(10);

                errorCode = StringUtil.convertHexToString(errorCode);

                String ct = convertHexToByte(currentTemperature);
                String st = convertHexToByte(setTemperature);

                if ("0".equals(mode)) {
                    mode = "停止工作";
                } else if ("1".equals(mode)) {
                    mode = "制冷";
                } else if ("2".equals(mode)) {
                    mode = "制热";
                }

                /*

                0x30：无故障
                 0x31：传感器断路
                 0x32：传感器短路
                  0x33：温度超限
                 */
                if ("0".equals(errorCode)) {
                    errorCode = "无故障";
                } else if ("1".equals(errorCode)) {
                    errorCode = "传感器断路";
                } else if ("2".equals(errorCode)) {
                    errorCode = "传感器短路";
                } else if ("3".equals(errorCode)) {
                    errorCode = "温度超限";
                }
                refreshDataList(addCode, mode, st, ct, errorCode);
            }

            @Override
            public void onFile(String msg,String tuneNO, String orderNO) {
                ToastUtils.showShort("获取失败，" + msg);
            }
        });
        manager.setData(code);
        manager.execute();
    }

    /**
     * 温度值转换
     * 将16进制字节转化成带符号的整型数据
     * 比如0A -> 10,80 -> -127
     *
     * @param hexTemp 0A
     * @return
     */
    private String convertHexToByte(String hexTemp) {
        int ctInt = Integer.parseInt(hexTemp, 16);
        if (ctInt > 127) {
            ctInt = ctInt - 256;
        }
//        return ctInt + "";

        return (int) Byte.parseByte(ctInt + "", 10) + "";
    }

    private void initView() {
        mAdater = new SimpleTextRvAdapter(dataList);
        recyclerView.setAdapter(mAdater);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdater.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onClick(View v, int position) {
                switch (position) {
                    case 0:
                        showAddressCodeDialog();
                        break;
                    case 1:
                        showModeDialog();
                        break;
                    case 2:
                        showSetTempDialog();
                        break;
                }
            }
        });
    }

    /**
     * 设置温度
     */
    private void showSetTempDialog() {
        final InputDialog dialog = new InputDialog(this, R.style.MyDialog, InputType.TYPE_CLASS_NUMBER);
        dialog.show();
        String[] split = dataList.get(2).split(":");
        if (split.length == 1) {
            dialog.setCurrentValue("");
        } else {
            dialog.setCurrentValue(split[1]);
        }
        dialog.setOkOnClickListenter(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String inputContent = dialog.getInputContent();

                if (TextUtils.isEmpty(inputContent)) {
                    ToastUtils.showShort("输入不能为空");
                    return;
                }

                int i = Integer.parseInt(inputContent);
                if (i > 65) {
                    ToastUtils.showShort("温度设置不能超过65度");
                    dialog.setCurrentValue("65");
                    return;
                }

                if (i < -35) {
                    ToastUtils.showShort("温度设置不能低于-35度");
                    dialog.setCurrentValue("-35");
                    return;
                }

                dataList.set(2, SETTEMPERATURE + inputContent);
                mAdater.notifyDataSetChanged();
                dialog.dismiss();
            }
        });
        dialog.setCancelOnClickListenre(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setTitle("设置温度 (-35~65之间)");
        dialog.setEditLength(3);
        dialog.setEditFilter("-0123456789");
    }

    private void showAddressCodeDialog() {
        final String[] items = {"00", "01", "02", "03"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String addressCode = items[which];
                dataList.set(0, ADDRESS_CODE + addressCode);
                mAdater.notifyDataSetChanged();
                getInfo(addressCode);
            }
        });
        builder.create().show();
    }

    private void showModeDialog() {
        final String[] items = {"停止工作", "制冷", "制热"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    dataList.set(1, MODE + "停止工作");
                } else if (which == 1) {
                    dataList.set(1, MODE + "制冷");
                } else if (which == 2) {
                    dataList.set(1, MODE + "制热");
                }
                mAdater.notifyDataSetChanged();
            }
        });
        builder.create().show();
    }
}
